<?php
namespace logic\cyf;

use frontend\controllers\common;
use frontend\models\cyf\User;
use servers\JwtServer;
use servers\SmsServer;

class LoginLogic
{
    /**
     * 登录
     * @param $params
     * @return array
     * @name cyf
     */
    public static function login($params)
    {
        $user = User::login($params);
        if($user){
            $password = common::unlock_url($user['password']); //密码解密
            if($params['password'] != $password) throw new \Exception('手机号或密码错误');//抛出错误
        }
            return JwtServer::jwtEncode($user['id']);

    }

    /**
     * 用户注册
     * @param $params
     * @return array
     * @name  cyf
     */
    public static function iegister($params)
    {
        $phone  = $params['phone'];
        $cache = \Yii::$app->cache;
        $sendSmsCode = 'smscode'.$phone;//缓存验证码变量
        $code = $cache->get($sendSmsCode);//得到发送的验证码
        if($code != $params['code']) throw new \Exception('验证码错误');
        $res = User::createUser($phone);//调用模型添加数据放法
        if(!$res) throw new \Exception('注册失败');
        $user = User::getUserOneBYPhone($phone);//查询用户信息
        return $user->id;
    }

    /**
     * 设置密码逻辑
     * @param $params
     * @return array
     * @name cyf
     */
    public static function setPassword($params)
    {
        $res = User::createPassword($params);
        if(!$res) throw new \Exception('设置密码失败');
        return true;
    }


    /**
     * 发送验证码逻辑
     * @param $phone
     */
    public static function sendSms($phone)
    {
        $sms = SmsServer::sendSms($phone,true);
        if(!$sms['status'] == 0) throw new \Exception($sms['msg']);
        return $sms['data'];
    }
}